<?php

/**
 * User: day
 * Date: 2018/08/07
 * Time: 23:04
 * Description:
 */

namespace App\Console\Commands\ThirdOrder;


use App\Services\ThirdAPI\GameApiService;
use App\Services\ThirdAPI\SGAPIService;
use App\Services\UserService;
use common\utils\RedisKeys;
use common\enum\CommonEnum;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;


class SGOrderProcessor extends BaseOrderProcessor {
    protected $signature = self::PREFIX . 'sg {--type=}';
    protected $description = 'SG注单拉取';

    public $gameNames;
    public $sgService;
    // 拉取注单的区间长度，比如从 4:00 - 5:00 一个小时的长度，根据注单量调整
    public $timeInterval = 60 * 60;
    // 自动重拉更新锁 redis key
    public $lockRedisKey = RedisKeys::SG_LOCK_AUTOFIX;
    // 拉取注单更新时间 redis key
    public $updateRedisKey = RedisKeys::SG_UPDATE_TIME;
    // 当前最新的拉取注单更新时间
    public $latestUpdateKey;

    //來源:PC
    const DEVICE_WEB = 'Web';
    //來源:PC
    const DEVICE_H5 = 'Mobile';

    /**
     * 初始化信息，子类需要重写这个方法
     */
    public function init($argv = null)
    {
        // 必须调用父类init，初始化公共信息
        parent::init();
        $this->sgService = new SGAPIService();
        $this->partnerName = "SG";
        $info = GameApiService::getApiPartnerInfoByName($this->partnerName);
        $this->partnerID = $info['id'];
        $this->orderType = self::ORDER_TYPE_EGAME;
        $this->reportOrderType = self::GAME_TYPE_EGAME;
        $this->gameNames = $this->sgService->getSGGameNames();
        $this->userInfos = [];
    }

    /**
     * 向第三方API抓取数据
     */
    public function catchData()
    {
        $startTime = OrderStrategy::getUpdateKey($this->lockRedisKey, $this->updateRedisKey);
        $startTime = strtotime($startTime);
        $this->latestUpdateKey = $endTime = min(time(), $startTime + $this->timeInterval);
//        qq([date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', $endTime)]);
        Log::info('load SG order:'.json_encode([date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', $endTime)]));
        $data = $this->sgService->getSGOrders($startTime, $endTime);
        return $data;
    }

    /**
     * 处理数据
     * 不可以放复杂操作，因为拉取到的每个数据都会经过 load 加载
     */
    public function load($data)
    {
        $this->originData = json_encode($data);
        $this->orderNumber = $data["ticketId"];
        $this->betTime = transfer_timezone($data['ticketTime']);
        $this->betMoney = round(amount_format($data['betAmount'],true), 0);//投注额
        //注单状态（是否已结束）
        if($data['completed'] == true){
            $this->winLossMoney = round(amount_format($data['winLoss'],true), 0);//输赢
            $this->settleTime = $this->betTime;//结算时间
            $this->prizeMoney = round(amount_format($data['betAmount'] + $data['winLoss'],true) , 0);//派奖
            $this->validMoney = $this->betMoney;
            $this->commonStatus = self::COMMON_STATUS_SETTLE;//注单状态:0=等待
        }else{
            $this->commonStatus = self::COMMON_STATUS_INVALID;//注单状态:2=结算
        }
        $this->apiUserName = strtolower($data['acctId']);//第三方用户名
        $this->contributeMoney = 0; //贡献  SG接口没有这个值
        $this->bonusMoney = 0; //奖金  SG拉取注单接口没有这个值，需要单独调用获取奖池金额接口，这里不记录
        $this->updateKey = $this->betTime;//updateKey（可以根据这个字段重新抓取数据）
        $this->reportTime = $data['ticketTime'];//第三方计算该注单的报表时间
        $this->apiStatus = 1;
        $this->gameCode = $data['gameCode'];
        $this->gameName = $this->gameNames[$data['gameCode']];
        $this->betContent = "";
        //来源
        if($data['channel'] == self::DEVICE_H5){
            $this->platform = CommonEnum::DEVICE_H5;
        }elseif($data['channel'] == self::DEVICE_WEB){
            $this->platform = CommonEnum::DEVICE_PC;
        }
    }


    /**
     * 过滤下注金额和中间金额为0的订单
     */
/*    public function removeRepeat($data){
        //有些游戏是:堆叠连续奖赏，连续爆炸会有机会获得连续奖赏，这个情况的betAmount(下注金额)是就会是0，当爆炸停止则会中止，此时订单的betAmount(下注金额)和输赢金额都为0
        foreach ($data as $k => $v){
            if($v['betAmount'] == 0 && $v['winLoss'] == 0){
                unset($data[$k]);
            }
        }
        return $data;
    }*/

    /*
     * 更新redis拉取注单ID
     */
    public function updateFlag($updateKey){
        Redis::connection()->set($this->updateRedisKey, date("Y-m-d H:i:s", $this->latestUpdateKey));
    }

    /**
     * 处理数据，每个子类需要根据第三方的单条数据内容来获取有用的信息
     */
    public function initFromData($data)
    {

    }

    /**
     * 修复数据内容，每个子类需要实现怎么修复数据内容
     */
    public function fixData($date)
    {

    }
}
